const express = require('express');
const router = express.Router();
const { createUser, getAllUsers, getPaginatedUsers, getUserById, updataUser, updataUserPassword, deleteUser, findByCredentials } = require('@/services/user.services')
const { sendResponse } = require('@/utils/tool')
const { expiresIn, cookieTokenName } = require('@/config/jwt.config')


/**
 * @swagger
 * /createUser:
 *   post:
 *     tags:
 *       - 用户管理
 *     summary: 创建用户
 *     description: 创建用户
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               account:
 *                 type: string
 *                 description: 账号
 *                 required: true
 *               password:
 *                 type: string
 *                 description: 密码
 *                 format: password
 *                 required: true
 *               roleIds:
 *                 type: string
 *                 description: 角色
 *               nickname:
 *                 type: string
 *                 description: 昵称
 *               email:
 *                 type: string
 *                 description: 邮箱
 *               phoneNumber:
 *                 type: string
 *                 description: 手机号
 *               avatar:
 *                 type: string
 *                 description: 头像地址
 *               frontCryptoState:
 *                 type: boolean
 *                 description: 前端是否加密
 *     responses:
 *       200:
 *         $ref: '#/components/responses/success'
 *       500:
 *         $ref: '#/components/responses/error'
 */
router.post('/createUser', async (req, res) => {
  try {
    let { account, password, nickname, email, phoneNumber, avatar, roleIds, frontCryptoState } = req.body
    if (!Array.isArray(roleIds)) {
      roleIds = roleIds && JSON.parse(roleIds)
    }
    let info = {
      account,
      password,
      nickname,
      email,
      phoneNumber,
      avatar,
      roleIds
    }

    let result = await createUser(info, frontCryptoState)
    sendResponse(req, res, result)
  } catch (error) {
    sendResponse(req, res, { code: 500 })
  }
})

/**
 * @swagger
 * /login:
 *   post:
 *     tags:
 *       - 用户管理
 *     summary: 登录
 *     description: 登录
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               account:
 *                 type: string
 *                 description: 账号
 *                 required: true
 *               password:
 *                 type: string
 *                 description: 密码
 *                 format: password
 *                 required: true
 *               frontCryptoState:
 *                 type: boolean
 *                 description: 前端是否加密
 *                 default: false
 *     responses:
 *       200:
 *         $ref: '#/components/responses/success'
 *       400:
 *         $ref: '#/components/responses/paramsBad'
 *       500:
 *         $ref: '#/components/responses/error'
 */
router.post('/login', async (req, res) => {
  try {
    let { account, password, frontCryptoState } = req.body
    let result = await findByCredentials(account, password, frontCryptoState)

    result.code == 200 && res.cookie(cookieTokenName, result.data.token, {
      httpOnly: true,
      maxAge: expiresIn * 1000
    })
    sendResponse(req, res, result)
  } catch (error) {
    sendResponse(req, res, { code: 500 })
  }
})

/**
 * @swagger
 * /getUserById/{id}:
 *   get:
 *     tags:
 *       - 用户管理
 *     summary: 获取用户信息
 *     description: 通过用户ID获取用户信息
 *     security:
 *       - authorization: []
 *     parameters:
 *       -
 *         name: id
 *         in: path
 *         description: 用户ID
 *         required: true
 *     responses:
 *       200:
 *         $ref: '#/components/responses/userInfo'
 *       500:
 *         $ref: '#/components/responses/error'
 *       400:
 *         $ref: '#/components/responses/paramsBad'
 *       401:
 *         $ref: '#/components/responses/unauthorized'
 */
router.get('/getUserById', async (req, res) => {
  try {
    let { id } = req.query
    let result = await getUserById(id)
    sendResponse(req, res, result)
  } catch (error) {
    sendResponse(req, res, { code: 500 })
  }
})

/**
 * @swagger
 * /getAllUsers:
 *   get:
 *     tags:
 *       - 用户管理
 *     summary: 获取所有用户信息
 *     description: 获取所有用户信息
 *     security:
 *       - authorization: []
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               order:
 *                 type: string
 *                 description: 排序字段 ASC/DESC
 *                 default: ASC
 *     responses:
 *       200:
 *         description: 返回所有用户信息
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 total:
 *                   type: number
 *                   description: 总数
 *                 list:
 *                   type: array
 *                   items:
 *                     $ref: '#/components/schemas/userInfo'
 *       500:
 *         $ref: '#/components/responses/error'
 *       400:
 *         $ref: '#/components/responses/paramsBad'
 *       401:
 *         $ref: '#/components/responses/unauthorized'
 */
router.get('/getAllUsers', async (req, res) => {
  try {
    let { order } = req.query
    let result = await getAllUsers(order)
    sendResponse(req, res, result)
  } catch (error) {
    sendResponse(req, res, { code: 500 })
  }
})


/**
 * @swagger
 * /getPaginatedUsers:
 *   get:
 *     tags:
 *       - 用户管理
 *     summary: 分页获取用户信息
 *     description: 分页获取用户信息
 *     security:
 *       - authorization: []
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               page:
 *                 type: number
 *                 description: 页码
 *                 default: 1
 *               pageSize:
 *                 type: number
 *                 description: 数量
 *                 default: 10
 *               order:
 *                 type: string
 *                 description: 排序字段 ASC/DESC
 *                 default: ASC
 *     responses:
 *       200:
 *         description: 返回所有用户信息
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 total:
 *                   type: number
 *                   description: 总数
 *                 list:
 *                   type: array
 *                   items:
 *                     $ref: '#/components/schemas/userInfo'
 *       500:
 *         $ref: '#/components/responses/error'
 *       400:
 *         $ref: '#/components/responses/paramsBad'
 *       401:
 *         $ref: '#/components/responses/unauthorized'
 */
router.get('/getPaginatedUsers', async (req, res) => {
  try {
    let { page, pageSize, order } = req.query
    let result = await getPaginatedUsers(page, pageSize, order)
    sendResponse(req, res, result)
  } catch (error) {
    sendResponse(req, res, { code: 500 })
  }
})

/**
 * @swagger
 * /updataUser:
 *   put:
 *     tags:
 *      - 用户管理
 *     summary: 更新用户
 *     description: 更新用户信息
 *     security:
 *       - authorization : []
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/updataUser'
 *     responses:
 *       200:
 *         description: 更新成功
 *       500:
 *         $ref: '#/components/responses/error'
 *       400:
 *         $ref: '#/components/responses/paramsBad'
 *       401:
 *         $ref: '#/components/responses/unauthorized'
 */
router.put('/updataUser', async (req, res) => {
  try {
    let userInfo = req.user
    let { nickname, email, phone, roleIds, frontCryptoState } = req.body
    if (!Array.isArray(roleIds)) {
      roleIds = roleIds && JSON.parse(roleIds)
    }
    let info = {
      ...userInfo,
      nickname: nickname ?? userInfo.nickname,
      email: email ?? userInfo.email,
      phone: phone ?? userInfo.phone,
      roleIds: roleIds ?? userInfo.roles.map(item => item.id)
    }

    let result = await updataUser(info.id, info, frontCryptoState)
    sendResponse(req, res, result)
  } catch (error) {
    sendResponse(req, res, { code: 500 })
  }
})

/**
 * @swagger
 * /updataUserPassword:
 *   put:
 *     tags:
 *       - 用户管理
 *     summary: 更新用户密码
 *     description: 更新用户密码
 *     security:
 *       - authorization: []
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               oldPassword:
 *                 type: string
 *                 description: 旧密码
 *               newPassword:
 *                 type: string
 *                 description: 新密码
 *               frontCryptoState:
 *                 type: boolean
 *                 description: 前端是否加密
 *     responses:
 *       200:
 *         description: 更新成功
 *       500:
 *         $ref: '#/components/responses/error'
 *       400:
 *         $ref: '#/components/responses/paramsBad'
 *       401:
 *         $ref: '#/components/responses/unauthorized'
 */
router.put('/updataUserPassword', async (req, res) => {
  try {
    let { oldPassword, newPassword, frontCryptoState } = req.body
    let userInfo = req.user

    let result = await updataUserPassword(userInfo.id, oldPassword, newPassword, frontCryptoState)
    sendResponse(req, res, result)
  } catch (error) {
    sendResponse(req, res, { code: 500 })
  }
})

/**
 * @swagger
 * /deleteUser:
 *   delete:
 *     tags:
 *       - 用户管理
 *     summary: 删除用户
 *     description: 删除用户
 *     security:
 *       - authorization: []
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               id:
 *                 type: string
 *                 description: 用户id
 *     responses:
 *       200:
 *         description: 删除用户成功
 *       500:
 *         $ref: '#/components/responses/error'
 *       400:
 *         $ref: '#/components/responses/paramsBad'
 *       401:
 *         $ref: '#/components/responses/unauthorized'
 */
router.delete('/deleteUser', async (req, res) => {
  try {
    let { id } = req.query
    let result = await deleteUser(id)
    sendResponse(req, res, result)
  } catch (error) {
    sendResponse(req, res, { code: 500 })
  }
})
module.exports = router;